import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type {
  ChatMessage,
  ChatSession,
  ChatSessionDetail,
  ApiKeyConfig,
  ApiKeyResponse,
  ChatStatus,
  AIModel,
  CreateSessionRequest,
  UpdateSessionTitleRequest,
  SaveMessageRequest
} from '@/types/aiChat'
import type { AIRole, LanguageDetection } from '@/types/aiRole'
import { PRESET_ROLES } from '@/types/aiRole'
import * as aiChatApi from '@/api/aiChat'

export const useAIChatStore = defineStore('aiChat', () => {
  // 状态
  const messages = ref<ChatMessage[]>([])
  const currentSession = ref<ChatSession | null>(null)
  const sessions = ref<ChatSession[]>([])
  const status = ref<ChatStatus>('idle')
  const streamingMessageId = ref<string | null>(null)
  const abortController = ref<AbortController | null>(null)
  const apiKeyConfig = ref<ApiKeyResponse | null>(null)
  const availableModels = ref<AIModel[]>([
    {
      value: 'THUDM/GLM-4.1V-9B-Thinking',
      label: 'GLM-4.1V-9B-Thinking',
      description: '智谱AI最新思维模型，支持复杂推理',
      free: false
    },
    {
      value: 'THUDM/GLM-Z1-9B-0414',
      label: 'GLM-Z1-9B-0414',
      description: '智谱AI高效对话模型',
      free: false
    }
  ])

  // ========== 角色管理状态 ==========
  const roles = ref<AIRole[]>([])
  const currentRole = ref<AIRole | null>(null)
  const customRoles = ref<AIRole[]>([])

  // 计算属性
  const hasApiKey = computed(() => !!apiKeyConfig.value?.hasApiKey)
  const currentModel = computed(() =>
    apiKeyConfig.value?.model || 'THUDM/GLM-4.1V-9B-Thinking'
  )
  const currentApiKey = computed(() =>
    apiKeyConfig.value?.maskedApiKey || ''
  )
  const isLoading = computed(() => status.value === 'loading')
  const isStreaming = computed(() => status.value === 'streaming')
  const canSendMessage = computed(() =>
    hasApiKey.value && status.value === 'idle'
  )

  // 角色相关计算属性
  const allRoles = computed(() => [...PRESET_ROLES, ...customRoles.value])
  const activeRole = computed(() =>
    currentRole.value || PRESET_ROLES.find(role => role.id === 'default') || PRESET_ROLES[0]
  )

  // ========== 角色管理方法 ==========

  // 简单的语言检测函数
  const detectLanguage = (text: string): LanguageDetection => {
    const chineseRegex = /[\u4e00-\u9fff]/
    const englishRegex = /[a-zA-Z]/

    const chineseCount = (text.match(chineseRegex) || []).length
    const englishCount = (text.match(englishRegex) || []).length
    const totalChars = text.length

    if (chineseCount > totalChars * 0.3) {
      return { language: 'zh', confidence: chineseCount / totalChars }
    } else if (englishCount > totalChars * 0.5) {
      return { language: 'en', confidence: englishCount / totalChars }
    } else {
      return { language: 'other', confidence: 0.5 }
    }
  }

  // 处理翻译助手的特殊逻辑
  const processTranslationMessage = (content: string): string => {
    const detection = detectLanguage(content)

    if (detection.language === 'zh') {
      return `请将以下中文翻译成英文，要求翻译准确、自然、符合英语表达习惯：\n\n${content}`
    } else if (detection.language === 'en') {
      return `请将以下英文翻译成中文，要求翻译准确、自然、符合中文表达习惯：\n\n${content}`
    } else {
      return `请将以下内容翻译成中文，要求翻译准确、自然：\n\n${content}`
    }
  }

  // 切换角色
  const switchRole = (roleId: string) => {
    const role = allRoles.value.find(r => r.id === roleId)
    if (role) {
      currentRole.value = role
      // 保存到localStorage
      localStorage.setItem('ai-chat-current-role', roleId)
      ElMessage.success(`已切换到${role.name}`)
    }
  }

  // 添加自定义角色
  const addCustomRole = (roleData: Omit<AIRole, 'id' | 'isCustom' | 'isActive' | 'createdAt' | 'updatedAt'>) => {
    const newRole: AIRole = {
      ...roleData,
      id: `custom-${Date.now()}`,
      isCustom: true,
      isActive: false,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }

    customRoles.value.push(newRole)
    saveCustomRoles()
    ElMessage.success(`角色"${newRole.name}"创建成功`)
    return newRole
  }

  // 更新自定义角色
  const updateCustomRole = (roleId: string, updates: Partial<AIRole>) => {
    const index = customRoles.value.findIndex(r => r.id === roleId)
    if (index !== -1) {
      customRoles.value[index] = {
        ...customRoles.value[index],
        ...updates,
        updatedAt: new Date().toISOString()
      }
      saveCustomRoles()
      ElMessage.success('角色更新成功')
    }
  }

  // 删除自定义角色
  const deleteCustomRole = (roleId: string) => {
    const index = customRoles.value.findIndex(r => r.id === roleId)
    if (index !== -1) {
      const roleName = customRoles.value[index].name
      customRoles.value.splice(index, 1)

      // 如果删除的是当前角色，切换到默认角色
      if (currentRole.value?.id === roleId) {
        switchRole('default')
      }

      saveCustomRoles()
      ElMessage.success(`角色"${roleName}"已删除`)
    }
  }

  // 保存自定义角色到localStorage
  const saveCustomRoles = () => {
    localStorage.setItem('ai-chat-custom-roles', JSON.stringify(customRoles.value))
  }

  // 加载自定义角色
  const loadCustomRoles = () => {
    try {
      const saved = localStorage.getItem('ai-chat-custom-roles')
      if (saved) {
        customRoles.value = JSON.parse(saved)
      }
    } catch (error) {
      console.error('Failed to load custom roles:', error)
    }
  }

  // 加载当前角色
  const loadCurrentRole = () => {
    try {
      const savedRoleId = localStorage.getItem('ai-chat-current-role')
      if (savedRoleId) {
        const role = allRoles.value.find(r => r.id === savedRoleId)
        if (role) {
          currentRole.value = role
        }
      }
    } catch (error) {
      console.error('Failed to load current role:', error)
    }
  }

  // 方法
  const sendMessage = async (content: string, options?: any) => {
    if (!hasApiKey.value) {
      throw new Error('API Key not configured')
    }

    if (status.value !== 'idle') {
      throw new Error('Another message is being processed')
    }

    // 创建用户消息
    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      role: 'user',
      content,
      timestamp: new Date()
    }
    
    messages.value.push(userMessage)
    status.value = 'loading'

    // 保存用户消息到会话（如果有当前会话）
    if (currentSession.value) {
      try {
        await saveMessageToCurrentSession('user', content)
      } catch (error) {
        console.error('Save user message error:', error)
      }
    }

    try {
      // 确保之前的流式传输已经完全停止
      if (streamingMessageId.value) {
        streamingMessageId.value = null
      }

      // 创建AI回复消息，使用更唯一的ID
      const aiMessage: ChatMessage = {
        id: `ai-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
        role: 'assistant',
        content: '',
        timestamp: new Date()
      }
      messages.value.push(aiMessage)
      streamingMessageId.value = aiMessage.id
      status.value = 'streaming'

      // 处理角色和消息内容
      let finalMessage = content
      const role = activeRole.value

      // 翻译助手特殊处理
      if (role.id === 'translator') {
        finalMessage = processTranslationMessage(content)
      } else if (role.prompt && role.id !== 'default') {
        // 其他角色添加系统提示词
        finalMessage = `${role.prompt}\n\n用户问题：${content}`
      }

      // 构建请求参数
      const requestData = options || {
        message: finalMessage,
        model: currentModel.value
      }

      // 如果没有指定message，使用处理后的消息
      if (!requestData.message) {
        requestData.message = finalMessage
      }

      // 发送SSE请求
      await aiChatApi.sendMessageStream(requestData, (chunk: string | any) => {
        // 流式更新AI消息内容
        const messageIndex = messages.value.findIndex(m => m.id === aiMessage.id)
        if (messageIndex !== -1) {
          // 检查是否是JSON格式的推理/回答内容
          if (typeof chunk === 'object' && chunk.type && chunk.content) {
            if (chunk.type === 'reasoning') {
              // 推理内容
              if (!messages.value[messageIndex].reasoning) {
                messages.value[messageIndex].reasoning = ''
              }
              messages.value[messageIndex].reasoning += chunk.content
            } else if (chunk.type === 'content') {
              // 回答内容
              messages.value[messageIndex].content += chunk.content
            }
          } else {
            // 向后兼容：纯文本内容
            messages.value[messageIndex].content += chunk
          }
        }
      }, (error: Error) => {
        // 错误处理和状态恢复 - 只影响当前消息
        const messageIndex = messages.value.findIndex(m => m.id === aiMessage.id)
        if (messageIndex !== -1) {
          messages.value[messageIndex].error = true
          messages.value[messageIndex].content = `错误: ${error.message}`
        }

        // 重置状态，确保界面可以继续使用
        status.value = 'idle'
        // 只有当前消息ID匹配时才重置streamingMessageId
        if (streamingMessageId.value === aiMessage.id) {
          streamingMessageId.value = null
        }

        ElMessage.error(`AI回复失败: ${error.message}`)
      })

      // 保存AI回复消息到会话
      const finalAiMessage = messages.value.find(m => m.id === aiMessage.id)
      if (finalAiMessage && finalAiMessage.content && !finalAiMessage.error && currentSession.value) {
        try {
          await saveMessageToCurrentSession('assistant', finalAiMessage.content)
        } catch (error) {
          console.error('Save AI message error:', error)
        }
      }

      status.value = 'idle'
    } catch (error) {
      console.error('Send message error:', error)
      status.value = 'error'
      
      // 移除失败的AI消息
      const aiMessageIndex = messages.value.findIndex(m => m.id === streamingMessageId.value)
      if (aiMessageIndex !== -1) {
        messages.value.splice(aiMessageIndex, 1)
      }
      
      ElMessage.error(`发送消息失败: ${error instanceof Error ? error.message : '未知错误'}`)
      throw error
    } finally {
      streamingMessageId.value = null
      abortController.value = null
    }
  }

  /**
   * 停止当前的流式传输
   */
  const stopStreaming = () => {
    if (status.value === 'streaming' && streamingMessageId.value) {
      // 标记当前消息为已停止
      const currentMessage = messages.value.find(m => m.id === streamingMessageId.value)
      if (currentMessage && !currentMessage.error) {
        currentMessage.content += '\n\n[已停止生成]'
      }

      // 重置状态 - 顺序很重要，先重置ID再重置状态
      streamingMessageId.value = null
      abortController.value = null
      status.value = 'idle'

      ElMessage.info('已停止生成')
    }
  }

  const saveApiKey = async (config: ApiKeyConfig) => {
    try {
      await aiChatApi.saveApiKey(config)
      await loadApiKey() // 重新加载配置
      ElMessage.success('API Key保存成功')
    } catch (error) {
      console.error('Save API key error:', error)
      ElMessage.error(`保存失败: ${error instanceof Error ? error.message : '未知错误'}`)
      throw error
    }
  }

  const loadApiKey = async () => {
    try {
      const response = await aiChatApi.getApiKey()
      // {{ AURA-X: Modify - 修复数据访问路径，从response改为response.data. Approval: 寸止(ID:fix-api-key-data-access). }}
      apiKeyConfig.value = response.data || response
    } catch (error) {
      console.error('Load API key error:', error)
      apiKeyConfig.value = { hasApiKey: false }
    }
  }

  const testApiKey = async () => {
    try {
      const response = await aiChatApi.testApiKey()
      // {{ AURA-X: Modify - 修复数据访问路径，确保正确获取测试结果. Approval: 寸止(ID:fix-api-key-data-access). }}
      const result = response.data || response
      if (result.valid) {
        ElMessage.success('API Key测试成功')
      } else {
        ElMessage.error(`API Key测试失败: ${result.message}`)
      }
      return result
    } catch (error) {
      console.error('Test API key error:', error)
      ElMessage.error(`测试失败: ${error instanceof Error ? error.message : '未知错误'}`)
      throw error
    }
  }

  const clearChat = async () => {
    // 如果有当前会话，调用后端API清空消息
    if (currentSession.value) {
      try {
        await aiChatApi.clearSessionMessages(currentSession.value.id)

        // 重新加载会话列表以更新消息数量
        await loadSessions()

        ElMessage.success('当前对话已清空')
      } catch (error) {
        console.error('Clear session messages error:', error)
        ElMessage.error(`清空对话失败: ${error instanceof Error ? error.message : '未知错误'}`)
        throw error
      }
    } else {
      // 没有当前会话时，只显示成功消息
      ElMessage.success('当前对话已清空')
    }

    // 清空前端状态
    messages.value = []
    status.value = 'idle'
    streamingMessageId.value = null
  }

  const retryLastMessage = async () => {
    if (messages.value.length < 2) return

    // 找到最后一条用户消息
    const lastUserMessage = [...messages.value]
      .reverse()
      .find(m => m.role === 'user')

    if (lastUserMessage) {
      // 移除最后一条AI消息（如果存在且有错误）
      const lastMessage = messages.value[messages.value.length - 1]
      if (lastMessage.role === 'assistant' && lastMessage.error) {
        messages.value.pop()
      }

      await sendMessage(lastUserMessage.content)
    }
  }

  // ========== 会话管理功能 ==========

  /**
   * 创建新会话
   */
  const createNewSession = async (title?: string) => {
    try {
      const sessionData: CreateSessionRequest = {
        title: title || '新对话',
        model: currentModel.value
      }

      const response = await aiChatApi.createSession(sessionData)
      // {{ AURA-X: Modify - 修复数据访问路径，确保正确获取新会话数据. Approval: 寸止(ID:fix-ai-chat-data-access). }}
      const newSession = response.data || response

      if (!newSession) {
        throw new Error('创建会话失败：服务器返回空数据')
      }

      // 更新会话列表 - 添加类型安全检查
      if (sessions.value && Array.isArray(sessions.value)) {
        sessions.value.unshift(newSession)
      }

      // 切换到新会话
      await switchToSession(newSession.id)

      ElMessage.success('新对话已创建')
      return newSession
    } catch (error) {
      console.error('Create session error:', error)

      // 检查是否是网络错误（后端未启动）
      if (error instanceof Error && (
        error.message.includes('fetch') ||
        error.message.includes('Network') ||
        error.message.includes('ERR_CONNECTION_REFUSED') ||
        error.message.includes('Failed to fetch')
      )) {
        ElMessage.error('无法连接到服务器，请检查后端服务是否启动')
      } else {
        ElMessage.error(`创建对话失败: ${error instanceof Error ? error.message : '未知错误'}`)
      }
      throw error
    }
  }

  /**
   * 加载会话列表
   */
  const loadSessions = async () => {
    try {
      const response = await aiChatApi.getSessions()
      // {{ AURA-X: Modify - 修复数据访问路径，从response改为response.data. Approval: 寸止(ID:fix-ai-chat-data-access). }}
      sessions.value = response.data || response || []
    } catch (error) {
      console.error('Load sessions error:', error)
      // 后端未启动时不显示错误消息，只在控制台记录
      sessions.value = []
    }
  }

  /**
   * 切换到指定会话
   */
  const switchToSession = async (sessionId: number) => {
    try {
      const response = await aiChatApi.getSessionDetail(sessionId)
      // {{ AURA-X: Modify - 修复数据访问路径，确保正确获取会话详情. Approval: 寸止(ID:fix-ai-chat-data-access). }}
      const sessionDetail = response.data || response

      // 更新当前会话
      currentSession.value = {
        id: sessionDetail.id,
        title: sessionDetail.title,
        model: sessionDetail.model,
        messageCount: sessionDetail.messageCount,
        createdAt: sessionDetail.createdAt,
        updatedAt: sessionDetail.updatedAt
      }

      // 更新消息列表
      messages.value = sessionDetail.messages.map(msg => ({
        id: msg.id.toString(),
        role: msg.role as 'user' | 'assistant',
        content: msg.content,
        timestamp: new Date(msg.createdAt)
      }))

      status.value = 'idle'
      streamingMessageId.value = null

    } catch (error) {
      console.error('Switch session error:', error)
      ElMessage.error(`切换对话失败: ${error instanceof Error ? error.message : '未知错误'}`)
      throw error
    }
  }

  /**
   * 更新会话标题
   */
  const updateSessionTitle = async (sessionId: number, title: string) => {
    try {
      await aiChatApi.updateSessionTitle(sessionId, { title })

      // 更新本地会话列表
      const sessionIndex = sessions.value.findIndex(s => s.id === sessionId)
      if (sessionIndex !== -1) {
        sessions.value[sessionIndex].title = title
      }

      // 更新当前会话
      if (currentSession.value?.id === sessionId) {
        currentSession.value.title = title
      }

      ElMessage.success('对话标题已更新')
    } catch (error) {
      console.error('Update session title error:', error)
      ElMessage.error(`更新标题失败: ${error instanceof Error ? error.message : '未知错误'}`)
      throw error
    }
  }

  /**
   * 删除会话
   */
  const deleteSessionById = async (sessionId: number) => {
    try {
      await aiChatApi.deleteSession(sessionId)

      // 从会话列表中移除
      sessions.value = sessions.value.filter(s => s.id !== sessionId)

      // 如果删除的是当前会话，只清空前端状态（不调用后端API）
      if (currentSession.value?.id === sessionId) {
        messages.value = []
        currentSession.value = null
        status.value = 'idle'
        streamingMessageId.value = null
      }

      ElMessage.success('对话已删除')
    } catch (error) {
      console.error('Delete session error:', error)
      ElMessage.error(`删除对话失败: ${error instanceof Error ? error.message : '未知错误'}`)
      throw error
    }
  }

  /**
   * 保存消息到当前会话
   */
  const saveMessageToCurrentSession = async (role: 'user' | 'assistant', content: string, tokenCount = 0) => {
    if (!currentSession.value) return

    try {
      const messageData: SaveMessageRequest = {
        role,
        content,
        tokenCount
      }

      await aiChatApi.saveMessage(currentSession.value.id, messageData)

      // 更新会话的消息数量
      currentSession.value.messageCount += 1

      // 更新会话列表中的对应项
      const sessionIndex = sessions.value.findIndex(s => s.id === currentSession.value!.id)
      if (sessionIndex !== -1) {
        sessions.value[sessionIndex].messageCount += 1
        sessions.value[sessionIndex].lastMessage = content.length > 50 ? content.substring(0, 50) + '...' : content
        sessions.value[sessionIndex].lastMessageRole = role
        sessions.value[sessionIndex].lastMessageTime = new Date().toISOString()
      }

    } catch (error) {
      console.error('Save message error:', error)
      // 检查是否是权限错误
      if (error instanceof Error && error.message.includes('403')) {
        console.warn('保存消息权限不足，可能是JWT token过期')
      }
      // 不显示错误消息，因为这是后台操作，不影响用户体验
    }
  }

  // 初始化时加载API Key配置、会话列表和角色数据
  loadApiKey()
  loadSessions()
  loadCustomRoles()
  loadCurrentRole()

  return {
    // 状态
    messages,
    currentSession,
    sessions,
    status,
    streamingMessageId,
    apiKeyConfig,
    availableModels,

    // 计算属性
    hasApiKey,
    currentModel,
    currentApiKey,
    isLoading,
    isStreaming,
    canSendMessage,

    // 角色相关计算属性
    allRoles,
    activeRole,

    // 方法
    sendMessage,
    stopStreaming,
    saveApiKey,
    loadApiKey,
    testApiKey,
    clearChat,
    retryLastMessage,

    // 会话管理方法
    createNewSession,
    loadSessions,
    switchToSession,
    updateSessionTitle,
    deleteSessionById,
    saveMessageToCurrentSession,

    // 角色管理方法
    switchRole,
    addCustomRole,
    updateCustomRole,
    deleteCustomRole,
    loadCustomRoles,
    loadCurrentRole
  }
})
